package com.yincheng.oes.attachment.service;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.javatuples.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yincheng.oes.attachment.entity.Attachment;
import com.yincheng.oes.attachment.mapper.AttachmentMapper;

@Service
public class AttachServiceImpl implements AttachService {

    private static final String DEFAULT_ROOT_KEY = "ques_img";

    @Autowired
    private AttachmentMapper attachmentMapper;

    /**
     * 上传图片 并返回图片唯一地址
     */
    @Override
    @Transactional
    public List<Attachment> uploadPic(List<Pair<String, InputStream>> files, String areaId)
            throws IOException {
        List<Attachment> list = new ArrayList<>();
        for (Pair<String, InputStream> pair : files) {
            Attachment attachment = uploadPic(areaId, pair);
            list.add(attachment);
        }
        return list;
    }

    private Attachment uploadPic(String areaId, Pair<String, InputStream> file) throws IOException {
        Attachment attachment = new Attachment();

        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String format = df.format(new Date());
        String address = UUID.randomUUID().toString().toUpperCase();
        String fileName = file.getValue0();
        String fileType = FilenameUtils.getExtension(fileName).toLowerCase();
        String downloadUrl = format + "/" + address + "." + fileType;

        attachment.setAttachmentId(address);
        attachment.setAreaId(areaId);
        attachment.setFileName(fileName);
        attachment.setFileType(fileType);
        attachment.setStoreTime(new Date());
        attachment.setRootKey(DEFAULT_ROOT_KEY);
        attachment.setDownloadUrl(downloadUrl);

        //生成文件内容
        File srcFile = getSrcFile(attachment);
        InputStream is = file.getValue1();
        long fileSize = IO.writeInputStreamToFile(is, srcFile);
        attachment.setFileSize(fileSize);

        attachmentMapper.insert(attachment);
        return attachment;
    }

    /**
     * 根据地址导出文件到输出流
     */
    @Override
    public void exportToOutputStream(String address, OutputStream os) {
        Validate.notBlank(address, "address must not blank.");
        Attachment attachment = attachmentMapper.selectByPrimaryKey(address);
        try {
            File srcFile = getSrcFile( attachment);
            FileInputStream fileInputStream = new FileInputStream(srcFile);
            IOUtils.copy(fileInputStream, os);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File getSrcFile(Attachment attachment) {
        String rootKey=attachment.getRootKey();
        if (StringUtils.isEmpty(rootKey)){
            rootKey = DEFAULT_ROOT_KEY;
        }
        String rootDirectory = attachmentMapper.getRootDirectory(rootKey);
        File rootFile = new File(rootDirectory);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        return new File(rootFile, attachment.getDownloadUrl());
    }

    @Override
    public Attachment getAttachment(String address) {
        Validate.notBlank(address, "address must not blank.");
        return attachmentMapper.selectByPrimaryKey(address);
    }

    @Override
    public List<Attachment> getAttachments(String areaId) {
        Validate.notBlank(areaId, "areaId must not blank.");
        return attachmentMapper.selectByAreaId(areaId);
    }

    @Override
    public void deleteAttachmentById(String attachmentId) {
        Validate.notBlank(attachmentId);
        Attachment attachment = attachmentMapper.selectByPrimaryKey(attachmentId);
        File destFile = getSrcFile( attachment);
        if (destFile.isDirectory()) { // 如果是 文件夹
            try {
                FileUtils.deleteDirectory(destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (destFile.isFile()) {// 如果是文件
            destFile.delete();
        }
        attachmentMapper.deleteByPrimaryKey(attachmentId);
    }
}
